package com.googlecode.imanager.client.form;

import com.googlecode.imanager.client.Container;
import com.googlecode.imanager.client.bridge.form.IButton;
import com.googlecode.imanager.client.event.KeyEvent;
import com.googlecode.imanager.client.event.KeyEventType;
import com.googlecode.imanager.client.event.MouseButton;
import com.googlecode.imanager.client.event.MouseEvent;
import com.googlecode.imanager.client.event.MouseEventType;
import com.googlecode.imanager.client.util.ControlState;
import com.googlecode.imanager.client.util.HasText;

/**
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public class Button extends FocusControl implements IButton, HasText {

    private static final long serialVersionUID = 1L;
    
    private String text = "";

    public Button() {
        super();
    }

    public Button(Container parent) {
        this();
        setParent(parent);
    }

    @Override
    public void onMouseEvent(MouseEvent e) {
        if (e.getTarget() == this
                && !e.isSimulated()){
            
            if (e.getEventType() == MouseEventType.MOUSE_ENTER){
                addState(ControlState.HOVER);
            }
            else if (e.getEventType() == MouseEventType.MOUSE_EXIT){
                removeState(ControlState.HOVER);
            }
            else if (e.getEventType() == MouseEventType.MOUSE_DOWN){
                if (e.getMouseButton() == MouseButton.LEFT_BUTTON){
                    addState(ControlState.PRESSED);
                }
            }
            else if (e.getEventType() == MouseEventType.MOUSE_UP){
                if (e.getMouseButton() == MouseButton.LEFT_BUTTON){
                    removeState(ControlState.PRESSED);
                }
            }
        }
        super.onMouseEvent(e);
    }

    @Override
    protected void handleDefault(KeyEvent e){
        super.handleDefault(e);
        if (!e.isPreventDefault()
                && e.getEventType() == KeyEventType.KEY_UP){
            
            if (e.getKeyCode() == KeyEvent.VK_ENTER
                    || e.getKeyCode() == KeyEvent.VK_SPACE){
                click();
            }
        }
    }
    
    public String getText() {
        return text;
    }

    public void setText(String text) {
        if (text == null){
            text = "";
        }
        if (!this.text.equals(text)){
            this.text = text;
            getBridge().setText(text);
        }
    }

    @Override
    public Button clone() {
        return (Button) super.clone();
    }

    @Override
    protected IButton getBridge() {
        return (IButton) lookupBridge();
    }
        
}
